package com.smart.community.device.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.smart.community.commons.result.Result;
import com.smart.community.device.entity.Device;
import com.smart.community.device.service.IDeviceService;
import com.smart.community.device.vo.DeviceVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 设备管理控制器
 * @author Wu.Liang
 * @since 2024-12-21
 */
@RestController
@RequestMapping("/device")
@Slf4j
@Tag(name = "设备管理", description = "设备管理相关接口")
public class DeviceController {
    
    @Autowired
    private IDeviceService deviceService;
    
    /**
     * 创建设备
     */
    @PostMapping
    @Operation(summary = "创建设备", description = "创建新的设备")
    public Result<Void> createDevice(
            @Parameter(description = "设备信息") @RequestBody @Valid Device device) {
        try {
            log.info("创建设备，设备信息：{}", device);
            boolean result = deviceService.createDevice(device);
            if (result) {
                return Result.success();
            } else {
                return Result.fail("创建失败");
            }
        } catch (Exception e) {
            log.error("创建设备失败", e);
            return Result.fail("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询设备列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询设备列表", description = "根据条件分页查询设备列表")
    public Result<IPage<DeviceVO>> getDevicePage(
            @Parameter(description = "当前页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "设备名称") @RequestParam(required = false) String deviceName,
            @Parameter(description = "设备类型") @RequestParam(required = false) Integer deviceType,
            @Parameter(description = "设备状态") @RequestParam(required = false) Integer deviceStatus,
            @Parameter(description = "社区ID") @RequestParam(required = false) Long communityId) {
        try {
            log.info("分页查询设备列表，当前页：{}，每页大小：{}", current, size);
            IPage<DeviceVO> result = deviceService.getDevicePage(current, size, deviceName, deviceType, deviceStatus, communityId);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询设备列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据社区ID查询设备列表
     */
    @GetMapping("/queryByCommunity")
    @Operation(summary = "根据社区ID查询设备列表", description = "支持类型和状态过滤")
    public Result<?> queryDevicesByCommunity(
            @Parameter(description = "社区ID列表，逗号分隔") @RequestParam String communityIds,
            @Parameter(description = "设备类型") @RequestParam(required = false) Integer deviceType,
            @Parameter(description = "设备状态") @RequestParam(required = false) Integer deviceStatus,
            @RequestParam(required = false, defaultValue = "false") Boolean groupByType) {
        try {
            if (communityIds == null || communityIds.trim().isEmpty()) {
                return Result.fail("参数communityIds不能为空");
            }
            
            List<Long> communityIdList = new java.util.ArrayList<>();
            for (String id : communityIds.split(",")) {
                if (org.springframework.util.StringUtils.hasText(id)) {
                    communityIdList.add(Long.valueOf(id.trim()));
                }
            }
            
            if (communityIdList.isEmpty()) {
                return Result.fail("有效的社区ID不能为空");
            }
            
            if (Boolean.TRUE.equals(groupByType)) {
                Map<Integer, List<DeviceVO>> groupedDevices = deviceService.getDevicesGroupedByType(communityIdList, deviceStatus);
                return Result.success(groupedDevices);
            } else {
                List<DeviceVO> deviceList = deviceService.getDevicesByCommunityIds(communityIdList, deviceType, deviceStatus);
                return Result.success(deviceList);
            }
        } catch (Exception e) {
            log.error("根据社区ID查询设备失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新设备
     */
    @PutMapping("/{deviceId}")
    @Operation(summary = "更新设备", description = "更新设备信息")
    public Result<Void> updateDevice(
            @Parameter(description = "设备ID") @PathVariable Long deviceId,
            @Parameter(description = "设备信息") @RequestBody @Valid Device device) {
        try {
            log.info("更新设备，设备ID：{}，设备信息：{}", deviceId, device);
            device.setId(deviceId);
            boolean result = deviceService.updateDevice(device);
            if (result) {
                return Result.success();
            } else {
                return Result.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新设备失败", e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新设备状态
     */
    @PutMapping("/{deviceId}/status")
    @Operation(summary = "更新设备状态", description = "更新设备状态")
    public Result<Void> updateDeviceStatus(
            @Parameter(description = "设备ID") @PathVariable Long deviceId,
            @Parameter(description = "设备状态：0-离线，1-在线，2-故障，3-维护") @RequestParam Integer deviceStatus) {
        try {
            log.info("更新设备状态，设备ID：{}，状态：{}", deviceId, deviceStatus);
            boolean result = deviceService.updateDeviceStatus(deviceId, deviceStatus);
            if (result) {
                return Result.success();
            } else {
                return Result.fail("更新失败");
            }
        } catch (Exception e) {
            log.error("更新设备状态失败", e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取设备统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取设备统计信息", description = "获取设备统计信息")
    public Result<Object> getDeviceStatistics(
            @Parameter(description = "社区ID") @RequestParam(required = false) Long communityId) {
        try {
            log.info("获取设备统计信息，社区ID：{}", communityId);
            Object statistics = deviceService.getDeviceStatistics(communityId);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取设备统计信息失败", e);
            return Result.fail("获取失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取设备详情
     */
    @GetMapping("/{deviceId}")
    @Operation(summary = "获取设备详情", description = "根据设备ID获取设备详细信息")
    public Result<DeviceVO> getDeviceDetail(
            @Parameter(description = "设备ID") @PathVariable Long deviceId) {
        try {
            log.info("获取设备详情，设备ID：{}", deviceId);
            DeviceVO device = deviceService.getDeviceDetail(deviceId);
            if (device == null) {
                return Result.fail("设备不存在");
            } else {
                return Result.success(device);
            }
        } catch (Exception e) {
            log.error("获取设备详情失败", e);
            return Result.fail("获取失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新设备状态
     */
    @PutMapping("/batch/status")
    @Operation(summary = "批量更新设备状态", description = "批量更新多个设备的状态")
    public Result<Void> batchUpdateDeviceStatus(
            @Parameter(description = "设备ID列表") @RequestBody List<Long> deviceIds,
            @Parameter(description = "设备状态") @RequestParam Integer deviceStatus) {
        try {
            log.info("批量更新设备状态，设备ID列表：{}，状态：{}", deviceIds, deviceStatus);
            boolean result = deviceService.batchUpdateDeviceStatus(deviceIds, deviceStatus);
            if (result) {
                return Result.success();
            } else {
                return Result.fail("批量更新失败");
            }
        } catch (Exception e) {
            log.error("批量更新设备状态失败", e);
            return Result.fail("批量更新失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除设备
     */
    @DeleteMapping("/{deviceId}")
    @Operation(summary = "删除设备", description = "删除指定设备")
    public Result<Void> deleteDevice(
            @Parameter(description = "设备ID") @PathVariable Long deviceId) {
        try {
            log.info("删除设备，设备ID：{}", deviceId);
            boolean result = deviceService.deleteDevice(deviceId);
            if (result) {
                return Result.success();
            } else {
                return Result.fail("删除失败");
            }
        } catch (Exception e) {
            log.error("删除设备失败", e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }
}
